package ch.six4rty.doodle.oauth
{
	import ch.six4rty.doodle.events.OAuthEvent;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	
	import nl.demonsters.debugger.MonsterDebugger;
	
	import org.flaircode.oauth.IOAuth;
	import org.flaircode.oauth.OAuth;
	import org.iotashan.oauth.OAuthConsumer;
	import org.iotashan.oauth.OAuthRequest;
	import org.iotashan.oauth.OAuthToken;
	import org.iotashan.utils.OAuthUtil;

	public class OAuthHelper extends EventDispatcher
	{
		private static const BASE_URL		:String		= "http://www.doodle.com/api1/oauth/";
		
		private var _oauth					:IOAuth;
		private var _loader					:URLLoader;
		private var _request				:URLRequest;
		
		private var _consumerKey			:String;
		private var _consumerSecret			:String;
		private var _requestToken			:OAuthToken;
		private var _accessToken			:OAuthToken;
		
		
		public function OAuthHelper( key:String, secret:String)
		{
			_consumerKey					= key;
			_consumerSecret					= secret;
			
			_oauth							= new OAuth( _consumerKey, _consumerSecret );
			_loader							= _oauth.getRequestToken( BASE_URL + "requesttoken" );
			_loader.addEventListener( Event.COMPLETE, requestTokenHandler );
		}
		
		private function requestTokenHandler (e:Event ):void
		{
			_loader.removeEventListener( Event.COMPLETE, requestTokenHandler );
			_requestToken 	= OAuthUtil.getTokenFromResponse(e.currentTarget.data as String);
			MonsterDebugger.trace(this, _requestToken, 0x0000ff );
			MonsterDebugger.trace(this, _oauth, 0x0000ff );
			
			_loader							= _oauth.getAccessToken( BASE_URL + "accesstoken", requestToken, ["oauth_token"] );
			_loader.addEventListener( Event.COMPLETE, accessTokenHandler );
		}
		
		private function accessTokenHandler ( e:Event ):void
		{
			_loader.removeEventListener( Event.COMPLETE, accessTokenHandler );
			
			_accessToken					= OAuthUtil.getTokenFromResponse( e.currentTarget.data as String );
			MonsterDebugger.trace(this, _accessToken, 0x0000ff );  
			
			dispatchEvent( new OAuthEvent( OAuthEvent.ACCESSTOKEN_RECEIVED ) );
		}
		
		public function get oauth():IOAuth
		{
			return _oauth
		}
		
		public function get requestToken ():OAuthToken
		{
			return _requestToken;
		}
		
		public function get accessToken ():OAuthToken
		{
			return _accessToken;
		}
	}
}